package mobile.game.core.gen.observer;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.protobuf.Descriptors.Descriptor;

import common.msg.Options;
import mobile.game.core.support.ClassFinder;
import mobile.game.core.support.observer.MsgReceiver;

public class GenMsgObserverInit {

	public static void main(String[] args) throws InstantiationException {
		// TODO Auto-generated method stub
		
		String packageName = "mobile.protobuf";
		Class<? extends Annotation> classAnno = null;
		Class<? extends Annotation> methodAnno = MsgReceiver.class;
		
		Map<Class<?>, List<Method>> msgMethods = new LinkedHashMap<>();
		
		List<Class<?>> sources = ClassFinder.getAllClass(packageName);
		
		for(Class<?> clazz : sources) {
			if(classAnno != null && !clazz.isAnnotationPresent(classAnno)) {
				continue;
			}
			
			Method[] ms = clazz.getMethods();
			List<Method> methods = new ArrayList<>();
			
			// 遍历所有方法，如果有DistrMethod注解，则加入list
			for(Method m : ms) {
				if(m.isAnnotationPresent(methodAnno)) {
					methods.add(m);
				}
			}
			
			// 如果有DistrMethod注解的方法，则加入待创建数据
			if(!methods.isEmpty()) {
				// 排序
				Collections.sort(methods, new Comparator<Method>() {

					@Override
					public int compare(Method o1, Method o2) {
						return o1.toString().compareTo(o2.toString());
					}
				});
				
				msgMethods.put(clazz, methods);
			}
		}
		
		for (Entry<Class<?>, List<Method>> entry : msgMethods.entrySet() ) {
//			Class<?> classz = entry.getKey();
			List<Method> methods = entry.getValue();
			
//			String className = classz.getSimpleName();
			
			for (Method m : methods) {
				
				try {
					Annotation anno = (Annotation)m.getAnnotation(methodAnno);
					Method mKey = methodAnno.getMethod("value");
					Class<?> messageClass = (Class<?>)mKey.invoke(anno);
					
					Object object = messageClass.getMethod("getDescriptor").invoke(null);
					Descriptor descriptor = (Descriptor)(object);
					int msgid = descriptor.getOptions().getExtension(Options.myOption);
					System.out.println("msgid:" + msgid);
					
				} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
		}
	}

}
